import Toast from '../component/Toast';
import {webSocket} from './webSocket';
import {getLoginSession} from '../plugin/loginSession';
import {wsMsg, debug} from '../config/config';
import {fromJson, toJson} from './utils';

let socket;

function open(channel, onMessageCallbak) {
	if(!socket) {
		let loginSession = getLoginSession();
		if(loginSession) {
			socket = webSocket({
				wsUrl: wsMsg() + '?port=' + loginSession.userId + '&channelId=' + channel,
				onOpen: () => {
					if(debug()) {
						console.log('websocket连接开启');
						Toast.show('websocket连接开启');
					}
				}, 
				onError: (e) => {
					if(debug()) {
						console.log('websocket连接异常', e);
						Toast.show('websocket连接异常');
					}
				}, 
				onClose: () => {
					if(debug()) {
						console.log('websocket连接关闭');
						Toast.show('websocket连接关闭');
					}
				}, 
				onMessage: (e) => {
					if(onMessageCallbak) {
						let msgResponse = fromJson(e.data);
						onMessageCallbak(msgResponse);
					} else {
						console.error('onMessageCallbak不存在');
					}
				}
			});
		}
	}
}

function close() {
	socket.close();
	socket = undefined;
}

function socket() {
	return socket;
}

function send(msgObj) {
	socket.send(toJson(msgObj)); 
}

export {
	open,
	close,
	send,
}
